package com.yss.system.controller;

import javax.servlet.http.HttpServletRequest;

import com.yss.common.core.utils.RsaUtils;
import com.yss.system.service.impl.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.yss.system.form.LoginBody;
import com.yss.system.form.RegisterBody;
import com.yss.common.core.domain.YssResponse;
import com.yss.common.core.utils.JwtUtils;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.security.auth.AuthUtil;
import com.yss.common.security.service.TokenService;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.system.api.model.LoginUser;

import static com.yss.common.core.web.domain.AjaxResult.success;

/**
 * token 控制
 */
@Slf4j
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("login")
    public YssResponse<?> login(@RequestBody LoginBody form) throws Exception {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), RsaUtils.decryptByPrivateKey(form.getPassword()));
        // 获取登录token
        return YssResponse.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public YssResponse<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                String username = JwtUtils.getUserName(token);
                // 删除用户缓存记录
                AuthUtil.logoutByToken(token);
                // 记录用户退出日志
                sysLoginService.logout(username);
            } catch (Exception ex) {
                log.error("退出登录失败" + ex.getMessage());
            }
        }
        return YssResponse.ok();
    }

    @PostMapping("refresh")
    public YssResponse<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return YssResponse.ok();
        }
        return YssResponse.ok();
    }

    @PostMapping("register")
    public YssResponse<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return YssResponse.ok();
    }
}
